<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java,SpringBoot,ThreadPool,Hystirx," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言平时接触过多线程开发的童鞋应该都或多或少了解过线程池，之前发布的《阿里巴巴 Java 手册》里也有一条：

可见线程池的重要性。
简单来说使用线程池有以下几个目的：

线程是稀缺资源，不能频繁的创建。
解耦作用；线程的创建于执行完全分开，方便维护。
应当将其放入一个池子中，可以给其他任务进行复用。

线程池原理谈到线程池就会想到池化技术，其中最核心的思想就是把宝贵的资源放到一个池子中；每次使">
<meta property="og:type" content="article">
<meta property="og:title" content="如何优雅的使用和理解线程池">
<meta property="og:url" content="http://crossoverjie.top/2018/07/29/java-senior/ThreadPool/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言平时接触过多线程开发的童鞋应该都或多或少了解过线程池，之前发布的《阿里巴巴 Java 手册》里也有一条：

可见线程池的重要性。
简单来说使用线程池有以下几个目的：

线程是稀缺资源，不能频繁的创建。
解耦作用；线程的创建于执行完全分开，方便维护。
应当将其放入一个池子中，可以给其他任务进行复用。

线程池原理谈到线程池就会想到池化技术，其中最核心的思想就是把宝贵的资源放到一个池子中；每次使">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2a867bea.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2a8dad64.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2a9bc566.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2aa81655.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2ab921db.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2ac0936c.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2accbbcf.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2add4d31.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2aeea439.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2b06ef2d.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2b69cd32.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d2b777ec3.jpg">
<meta property="og:updated_time" content="2019-05-07T18:48:07.675Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="如何优雅的使用和理解线程池">
<meta name="twitter:description" content="前言平时接触过多线程开发的童鞋应该都或多或少了解过线程池，之前发布的《阿里巴巴 Java 手册》里也有一条：

可见线程池的重要性。
简单来说使用线程池有以下几个目的：

线程是稀缺资源，不能频繁的创建。
解耦作用；线程的创建于执行完全分开，方便维护。
应当将其放入一个池子中，可以给其他任务进行复用。

线程池原理谈到线程池就会想到池化技术，其中最核心的思想就是把宝贵的资源放到一个池子中；每次使">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1d2a867bea.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/07/29/java-senior/ThreadPool/"/>

  <title> 如何优雅的使用和理解线程池 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                如何优雅的使用和理解线程池
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-07-29T02:00:16+08:00" content="2018-07-29">
              2018-07-29
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Java-进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Java 进阶</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/07/29/java-senior/ThreadPool/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/07/29/java-senior/ThreadPool/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/07/29/java-senior/ThreadPool/" class="leancloud_visitors" data-flag-title="如何优雅的使用和理解线程池">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1d2a867bea.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>平时接触过多线程开发的童鞋应该都或多或少了解过线程池，之前发布的《阿里巴巴 Java 手册》里也有一条：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2a8dad64.jpg" alt=""></p>
<p>可见线程池的重要性。</p>
<p>简单来说使用线程池有以下几个目的：</p>
<ul>
<li>线程是稀缺资源，不能频繁的创建。</li>
<li>解耦作用；线程的创建于执行完全分开，方便维护。</li>
<li>应当将其放入一个池子中，可以给其他任务进行复用。</li>
</ul>
<h2 id="线程池原理"><a href="#线程池原理" class="headerlink" title="线程池原理"></a>线程池原理</h2><p>谈到线程池就会想到池化技术，其中最核心的思想就是把宝贵的资源放到一个池子中；每次使用都从里面获取，用完之后又放回池子供其他人使用，有点吃大锅饭的意思。</p>
<p>那在 Java 中又是如何实现的呢？</p>
<p>在 JDK 1.5 之后推出了相关的 api，常见的创建线程池方式有以下几种：</p>
<ul>
<li><code>Executors.newCachedThreadPool()</code>：无限线程池。</li>
<li><code>Executors.newFixedThreadPool(nThreads)</code>：创建固定大小的线程池。</li>
<li><code>Executors.newSingleThreadExecutor()</code>：创建单个线程的线程池。</li>
</ul>
<a id="more"></a>
<p>其实看这三种方式创建的源码就会发现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newCachedThreadPool</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">0</span>, Integer.MAX_VALUE,</div><div class="line">                                  <span class="number">60L</span>, TimeUnit.SECONDS,</div><div class="line">                                  <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>实际上还是利用 <code>ThreadPoolExecutor</code> 类实现的。</p>
<p>所以我们重点来看下 <code>ThreadPoolExecutor</code> 是怎么玩的。</p>
<p>首先是创建线程的 api：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ThreadPoolExecutor(<span class="keyword">int</span> corePoolSize, <span class="keyword">int</span> maximumPoolSize, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue, RejectedExecutionHandler handler)</div></pre></td></tr></table></figure>
<p>这几个核心参数的作用：</p>
<ul>
<li><code>corePoolSize</code> 为线程池的基本大小。</li>
<li><code>maximumPoolSize</code> 为线程池最大线程大小。</li>
<li><code>keepAliveTime</code> 和 <code>unit</code> 则是线程空闲后的存活时间。</li>
<li><code>workQueue</code> 用于存放任务的阻塞队列。</li>
<li><code>handler</code> 当队列和最大线程池都满了之后的饱和策略。</li>
</ul>
<p>了解了这几个参数再来看看实际的运用。</p>
<p>通常我们都是使用:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">threadPool.execute(<span class="keyword">new</span> Job());</div></pre></td></tr></table></figure>
<p>这样的方式来提交一个任务到线程池中，所以核心的逻辑就是 <code>execute()</code> 函数了。</p>
<p>在具体分析之前先了解下线程池中所定义的状态，这些状态都和线程的执行密切相关：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2a9bc566.jpg" alt=""></p>
<ul>
<li><code>RUNNING</code> 自然是运行状态，指可以接受任务执行队列里的任务</li>
<li><code>SHUTDOWN</code> 指调用了 <code>shutdown()</code> 方法，不再接受新任务了，但是队列里的任务得执行完毕。</li>
<li><code>STOP</code> 指调用了 <code>shutdownNow()</code> 方法，不再接受新任务，同时抛弃阻塞队列里的所有任务并中断所有正在执行任务。</li>
<li><code>TIDYING</code> 所有任务都执行完毕，在调用 <code>shutdown()/shutdownNow()</code> 中都会尝试更新为这个状态。</li>
<li><code>TERMINATED</code> 终止状态，当执行 <code>terminated()</code> 后会更新为这个状态。</li>
</ul>
<p>用图表示为：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2aa81655.jpg" alt=""></p>
<p>然后看看 <code>execute()</code> 方法是如何处理的：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2ab921db.jpg" alt=""></p>
<ol>
<li>获取当前线程池的状态。</li>
<li>当前线程数量小于 coreSize 时创建一个新的线程运行。</li>
<li>如果当前线程处于运行状态，并且写入阻塞队列成功。</li>
<li>双重检查，再次获取线程状态；如果线程状态变了（非运行状态）就需要从阻塞队列移除任务，并尝试判断线程是否全部执行完毕。同时执行拒绝策略。</li>
<li>如果当前线程池为空就新创建一个线程并执行。</li>
<li>如果在第三步的判断为非运行状态，尝试新建线程，如果失败则执行拒绝策略。</li>
</ol>
<p>这里借助《聊聊并发》的一张图来描述这个流程：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2ac0936c.jpg" alt=""></p>
<h3 id="如何配置线程"><a href="#如何配置线程" class="headerlink" title="如何配置线程"></a>如何配置线程</h3><p>流程聊完了再来看看上文提到了几个核心参数应该如何配置呢？</p>
<p>有一点是肯定的，线程池肯定是不是越大越好。</p>
<p>通常我们是需要根据这批任务执行的性质来确定的。</p>
<ul>
<li>IO 密集型任务：由于线程并不是一直在运行，所以可以尽可能的多配置线程，比如 CPU 个数 * 2 </li>
<li>CPU 密集型任务（大量复杂的运算）应当分配较少的线程，比如 CPU 个数相当的大小。</li>
</ul>
<p>当然这些都是经验值，最好的方式还是根据实际情况测试得出最佳配置。</p>
<h3 id="优雅的关闭线程池"><a href="#优雅的关闭线程池" class="headerlink" title="优雅的关闭线程池"></a>优雅的关闭线程池</h3><p>有运行任务自然也有关闭任务，从上文提到的 5 个状态就能看出如何来关闭线程池。</p>
<p>其实无非就是两个方法 <code>shutdown()/shutdownNow()</code>。</p>
<p>但他们有着重要的区别：</p>
<ul>
<li><code>shutdown()</code> 执行后停止接受新任务，会把队列的任务执行完毕。</li>
<li><code>shutdownNow()</code> 也是停止接受新任务，但会中断所有的任务，将线程池状态变为 stop。</li>
</ul>
<blockquote>
<p>两个方法都会中断线程，用户可自行判断是否需要响应中断。</p>
</blockquote>
<p><code>shutdownNow()</code> 要更简单粗暴，可以根据实际场景选择不同的方法。</p>
<p>我通常是按照以下方式关闭线程池的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">long</span> start = System.currentTimeMillis();</div><div class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt;= <span class="number">5</span>; i++) &#123;</div><div class="line">    pool.execute(<span class="keyword">new</span> Job());</div><div class="line">&#125;</div><div class="line"></div><div class="line">pool.shutdown();</div><div class="line"></div><div class="line"><span class="keyword">while</span> (!pool.awaitTermination(<span class="number">1</span>, TimeUnit.SECONDS)) &#123;</div><div class="line">    LOGGER.info(<span class="string">"线程还在执行。。。"</span>);</div><div class="line">&#125;</div><div class="line"><span class="keyword">long</span> end = System.currentTimeMillis();</div><div class="line">LOGGER.info(<span class="string">"一共处理了【&#123;&#125;】"</span>, (end - start));</div></pre></td></tr></table></figure>
<p><code>pool.awaitTermination(1, TimeUnit.SECONDS)</code> 会每隔一秒钟检查一次是否执行完毕（状态为 <code>TERMINATED</code>），当从 while 循环退出时就表明线程池已经完全终止了。</p>
<h2 id="SpringBoot-使用线程池"><a href="#SpringBoot-使用线程池" class="headerlink" title="SpringBoot 使用线程池"></a>SpringBoot 使用线程池</h2><p>2018 年了，SpringBoot 盛行；来看看在 SpringBoot 中应当怎么配置和使用线程池。</p>
<p>既然用了 SpringBoot ，那自然得发挥 Spring 的特性，所以需要 Spring 来帮我们管理线程池：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TreadPoolConfig</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 消费队列线程</div><div class="line">     * <span class="doctag">@return</span></div><div class="line">     */</div><div class="line">    <span class="meta">@Bean</span>(value = <span class="string">"consumerQueueThreadPool"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> ExecutorService <span class="title">buildConsumerQueueThreadPool</span><span class="params">()</span></span>&#123;</div><div class="line">        ThreadFactory namedThreadFactory = <span class="keyword">new</span> ThreadFactoryBuilder()</div><div class="line">                .setNameFormat(<span class="string">"consumer-queue-thread-%d"</span>).build();</div><div class="line"></div><div class="line">        ExecutorService pool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">5</span>, <span class="number">5</span>, <span class="number">0L</span>, TimeUnit.MILLISECONDS,</div><div class="line">                <span class="keyword">new</span> ArrayBlockingQueue&lt;Runnable&gt;(<span class="number">5</span>),namedThreadFactory,<span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</div><div class="line"></div><div class="line">        <span class="keyword">return</span> pool ;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>使用时：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Resource</span>(name = <span class="string">"consumerQueueThreadPool"</span>)</div><div class="line"><span class="keyword">private</span> ExecutorService consumerQueueThreadPool;</div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">()</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">//消费队列</span></div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</div><div class="line">        consumerQueueThreadPool.execute(<span class="keyword">new</span> ConsumerQueueThread());</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其实也挺简单，就是创建了一个线程池的 bean，在使用时直接从 Spring 中取出即可。</p>
<h2 id="监控线程池"><a href="#监控线程池" class="headerlink" title="监控线程池"></a>监控线程池</h2><p>谈到了 SpringBoot，也可利用它 actuator 组件来做线程池的监控。</p>
<p>线程怎么说都是稀缺资源，对线程池的监控可以知道自己任务执行的状况、效率等。</p>
<p>关于 actuator 就不再细说了，感兴趣的可以看看<a href="http://t.cn/ReimM0o" target="_blank" rel="external">这篇</a>，有详细整理过如何暴露监控端点。</p>
<p>其实 ThreadPool 本身已经提供了不少 api 可以获取线程状态：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2accbbcf.jpg" alt=""></p>
<p>很多方法看名字就知道其含义，只需要将这些信息暴露到 SpringBoot 的监控端点中，我们就可以在可视化页面查看当前的线程池状态了。</p>
<p>甚至我们可以继承线程池扩展其中的几个函数来自定义监控逻辑：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2add4d31.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2aeea439.jpg" alt=""></p>
<p>看这些名称和定义都知道，这是让子类来实现的。</p>
<p>可以在线程执行前、后、终止状态执行自定义逻辑。</p>
<h2 id="线程池隔离"><a href="#线程池隔离" class="headerlink" title="线程池隔离"></a>线程池隔离</h2><blockquote>
<p>线程池看似很美好，但也会带来一些问题。</p>
</blockquote>
<p>如果我们很多业务都依赖于同一个线程池,当其中一个业务因为各种不可控的原因消耗了所有的线程，导致线程池全部占满。</p>
<p>这样其他的业务也就不能正常运转了，这对系统的打击是巨大的。</p>
<p>比如我们 Tomcat 接受请求的线程池，假设其中一些响应特别慢，线程资源得不到回收释放；线程池慢慢被占满，最坏的情况就是整个应用都不能提供服务。</p>
<p>所以我们需要将线程池<strong>进行隔离</strong>。</p>
<p>通常的做法是按照业务进行划分：</p>
<blockquote>
<p>比如下单的任务用一个线程池，获取数据的任务用另一个线程池。这样即使其中一个出现问题把线程池耗尽，那也不会影响其他的任务运行。</p>
</blockquote>
<h3 id="hystrix-隔离"><a href="#hystrix-隔离" class="headerlink" title="hystrix 隔离"></a>hystrix 隔离</h3><p>这样的需求 <a href="https://github.com/Netflix/Hystrix" target="_blank" rel="external">Hystrix</a> 已经帮我们实现了。</p>
<blockquote>
<p>Hystrix 是一款开源的容错插件，具有依赖隔离、系统容错降级等功能。</p>
</blockquote>
<p>下面来看看 <code>Hystrix</code> 简单的应用：</p>
<p>首先需要定义两个线程池，分别用于执行订单、处理用户。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * Function:订单服务</div><div class="line"> *</div><div class="line"> * <span class="doctag">@author</span> crossoverJie</div><div class="line"> *         Date: 2018/7/28 16:43</div><div class="line"> * <span class="doctag">@since</span> JDK 1.8</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandOrder</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">String</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(CommandOrder.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String orderName;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CommandOrder</span><span class="params">(String orderName)</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">        <span class="keyword">super</span>(Setter.withGroupKey(</div><div class="line">                <span class="comment">//服务分组</span></div><div class="line">                HystrixCommandGroupKey.Factory.asKey(<span class="string">"OrderGroup"</span>))</div><div class="line">                <span class="comment">//线程分组</span></div><div class="line">                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(<span class="string">"OrderPool"</span>))</div><div class="line"></div><div class="line">                <span class="comment">//线程池配置</span></div><div class="line">                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()</div><div class="line">                        .withCoreSize(<span class="number">10</span>)</div><div class="line">                        .withKeepAliveTimeMinutes(<span class="number">5</span>)</div><div class="line">                        .withMaxQueueSize(<span class="number">10</span>)</div><div class="line">                        .withQueueSizeRejectionThreshold(<span class="number">10000</span>))</div><div class="line"></div><div class="line">                .andCommandPropertiesDefaults(</div><div class="line">                        HystrixCommandProperties.Setter()</div><div class="line">                                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))</div><div class="line">        )</div><div class="line">        ;</div><div class="line">        <span class="keyword">this</span>.orderName = orderName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        LOGGER.info(<span class="string">"orderName=[&#123;&#125;]"</span>, orderName);</div><div class="line"></div><div class="line">        TimeUnit.MILLISECONDS.sleep(<span class="number">100</span>);</div><div class="line">        <span class="keyword">return</span> <span class="string">"OrderName="</span> + orderName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Function:用户服务</div><div class="line"> *</div><div class="line"> * <span class="doctag">@author</span> crossoverJie</div><div class="line"> *         Date: 2018/7/28 16:43</div><div class="line"> * <span class="doctag">@since</span> JDK 1.8</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandUser</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">String</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> Logger LOGGER = LoggerFactory.getLogger(CommandUser.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String userName;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CommandUser</span><span class="params">(String userName)</span> </span>&#123;</div><div class="line"></div><div class="line"></div><div class="line">        <span class="keyword">super</span>(Setter.withGroupKey(</div><div class="line">                <span class="comment">//服务分组</span></div><div class="line">                HystrixCommandGroupKey.Factory.asKey(<span class="string">"UserGroup"</span>))</div><div class="line">                <span class="comment">//线程分组</span></div><div class="line">                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(<span class="string">"UserPool"</span>))</div><div class="line"></div><div class="line">                <span class="comment">//线程池配置</span></div><div class="line">                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()</div><div class="line">                        .withCoreSize(<span class="number">10</span>)</div><div class="line">                        .withKeepAliveTimeMinutes(<span class="number">5</span>)</div><div class="line">                        .withMaxQueueSize(<span class="number">10</span>)</div><div class="line">                        .withQueueSizeRejectionThreshold(<span class="number">10000</span>))</div><div class="line"></div><div class="line">                <span class="comment">//线程池隔离</span></div><div class="line">                .andCommandPropertiesDefaults(</div><div class="line">                        HystrixCommandProperties.Setter()</div><div class="line">                                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))</div><div class="line">        )</div><div class="line">        ;</div><div class="line">        <span class="keyword">this</span>.userName = userName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">run</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">        LOGGER.info(<span class="string">"userName=[&#123;&#125;]"</span>, userName);</div><div class="line"></div><div class="line">        TimeUnit.MILLISECONDS.sleep(<span class="number">100</span>);</div><div class="line">        <span class="keyword">return</span> <span class="string">"userName="</span> + userName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<p><code>api</code> 特别简洁易懂，具体详情请查看官方文档。</p>
<p>然后模拟运行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    CommandOrder commandPhone = <span class="keyword">new</span> CommandOrder(<span class="string">"手机"</span>);</div><div class="line">    CommandOrder command = <span class="keyword">new</span> CommandOrder(<span class="string">"电视"</span>);</div><div class="line"></div><div class="line"></div><div class="line">    <span class="comment">//阻塞方式执行</span></div><div class="line">    String execute = commandPhone.execute();</div><div class="line">    LOGGER.info(<span class="string">"execute=[&#123;&#125;]"</span>, execute);</div><div class="line"></div><div class="line">    <span class="comment">//异步非阻塞方式</span></div><div class="line">    Future&lt;String&gt; queue = command.queue();</div><div class="line">    String value = queue.get(<span class="number">200</span>, TimeUnit.MILLISECONDS);</div><div class="line">    LOGGER.info(<span class="string">"value=[&#123;&#125;]"</span>, value);</div><div class="line"></div><div class="line"></div><div class="line">    CommandUser commandUser = <span class="keyword">new</span> CommandUser(<span class="string">"张三"</span>);</div><div class="line">    String name = commandUser.execute();</div><div class="line">    LOGGER.info(<span class="string">"name=[&#123;&#125;]"</span>, name);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<p>运行结果：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2b06ef2d.jpg" alt=""></p>
<p>可以看到两个任务分成了两个线程池运行，他们之间互不干扰。</p>
<p>获取任务任务结果支持同步阻塞和异步非阻塞方式，可自行选择。</p>
<p>它的实现原理其实容易猜到：</p>
<blockquote>
<p>利用一个 Map 来存放不同业务对应的线程池。</p>
</blockquote>
<p>通过刚才的构造函数也能证明：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2b69cd32.jpg" alt=""></p>
<p>还要注意的一点是：</p>
<blockquote>
<p>自定义的 Command 并不是一个单例，每次执行需要 new 一个实例，不然会报 <code>This instance can only be executed once. Please instantiate a new instance.</code> 异常。</p>
</blockquote>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>池化技术确实在平时应用广泛，熟练掌握能提高不少效率。</p>
<p>文末的 hystrix 源码：</p>
<p><a href="https://github.com/crossoverJie/Java-Interview/tree/master/src/main/java/com/crossoverjie/hystrix" target="_blank" rel="external">https://github.com/crossoverJie/Java-Interview/tree/master/src/main/java/com/crossoverjie/hystrix</a></p>
<p>最后插播个小广告：</p>
<p><a href="https://github.com/crossoverJie/Java-Interview" target="_blank" rel="external">Java-Interview</a> 截止目前将近 8K star。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d2b777ec3.jpg" alt=""></p>
<p>这次定个小目标：争取冲击 <code>1W star</code>。</p>
<p>感谢各位老铁的支持与点赞。</p>
<p><strong>欢迎关注公众号一起交流：</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
            <a href="/tags/SpringBoot/" rel="tag">#SpringBoot</a>
          
            <a href="/tags/ThreadPool/" rel="tag">#ThreadPool</a>
          
            <a href="/tags/Hystirx/" rel="tag">#Hystirx</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/23/java-senior/ConcurrentHashMap/" rel="next" title="HashMap? ConcurrentHashMap? 相信看完这篇没人能难住你！">
                <i class="fa fa-chevron-left"></i> HashMap? ConcurrentHashMap? 相信看完这篇没人能难住你！
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/03/netty/Netty(3)TCP-Sticky/" rel="prev" title="Netty(三) 什么是 TCP 拆、粘包？如何解决？">
                Netty(三) 什么是 TCP 拆、粘包？如何解决？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程池原理"><span class="nav-number">2.</span> <span class="nav-text">线程池原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#如何配置线程"><span class="nav-number">2.1.</span> <span class="nav-text">如何配置线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的关闭线程池"><span class="nav-number">2.2.</span> <span class="nav-text">优雅的关闭线程池</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringBoot-使用线程池"><span class="nav-number">3.</span> <span class="nav-text">SpringBoot 使用线程池</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#监控线程池"><span class="nav-number">4.</span> <span class="nav-text">监控线程池</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程池隔离"><span class="nav-number">5.</span> <span class="nav-text">线程池隔离</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#hystrix-隔离"><span class="nav-number">5.1.</span> <span class="nav-text">hystrix 隔离</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/07/29/java-senior/ThreadPool/';
      var disqus_title = "如何优雅的使用和理解线程池";
      var disqus_url = 'http://crossoverjie.top/2018/07/29/java-senior/ThreadPool/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
